package com.competition.web.admin.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.comm.util.contract.IFunction;
import com.common.util.ListConvertMap;
import com.common.util.MergeDataSource;
import com.competition.param.impl.LogSearch;
import com.competition.web.admin.service.ILogService;
import com.competition.web.admin.service.UmsAdminService;
import com.basic.service.contract.IBaseService;
import com.competition.web.entity.Log;
import com.competition.web.entity.UmsAdmin;
import com.controller.base.AbstractCommonController;
import com.controller.base.AbstractController;
import com.page.PageResponseData;


/**
 * 证书列表
 * 
 * @author 111
 */
@RestController
@RequestMapping("/admin/log")
public class LogController extends AbstractCommonController<Log, LogSearch> {

	private ILogService logService;

	private UmsAdminService userService;
	

	@Autowired
	public void setUserService(UmsAdminService userService) {
		this.userService = userService;
	}

	public LogController(ILogService logService) {

		this.logService = logService;
	}

	

	protected PageResponseData<Log> afterProcesser(PageResponseData<Log> list) {
		
		List<Log> logs = list.getData();
		
		if (0 == logs.size()) {
			return list;

		}
		
		List<UmsAdmin> users = userService.getDataByIds(logs.stream().map(e->e.getAdminId().intValue()).toArray(Integer[]::new));
		
		Map<Long, UmsAdmin> map = ListConvertMap.listToMap(users, UmsAdmin::getId);
		
		MergeDataSource<Log> dataSource = new MergeDataSource<>(logs);
		
		dataSource.merge(Log::getAdminId, map, new IFunction<Log, Log>() {
			
			@Override
			public <K, V> Log apply(Log t, Map<K, V> map) {
				
				UmsAdmin user = (UmsAdmin) map.get(t.getAdminId());
				
				t.setAdminName(user.getUsername());
				
				return t;
			}
		});
		
		return list;
	}
	
	protected LogSearch frontProcesser(LogSearch param) {
		
		Long endTime =  param.getEndTime();
		
		if (null != endTime) {
			if (0 > param.getEndTime().compareTo(param.getStartTime())) {
				throw new Error("开始时间不能小于结束时间");
			}
		}
		
		String userName = param.getUserName();
		
		if (null != userName) {
			List<UmsAdmin> users = this.userService.getIdsByParam(userName);
			if (null != users) {
				param.setUserIds(users.stream().map(e->e.getId().intValue()).toArray(Integer[]::new));
			}
		}
		
		return param;
	}

	@Override
	protected IBaseService<Log> getBaseService() {
		// TODO Auto-generated method stub
		return logService;
	}
	

}
